<template>
  <view>
    <!--有余额支付 -->
    <u-popup v-model="modelValue_s" zIndex="999" mode="bottom" border-radius="14" @close="closeThePopUpBox">
      <view class="w-full !bg-white !rounded-t-[1rem]" @click.stop>
        <view class="flex flex-col gap-4 py-5">
          <view class="flex justify-between items-center px-4">
            <view class="font-bold text-[1.25rem] text-[#171B24]">{{ title }}</view>
            <view class="pl-5" @click="closeThePopUpBox">
              <view class="size-6 bg-[#F4F6F8] flex justify-center items-center rounded-full">
                <u-icon name="close" color="#171B24" size="26"></u-icon>
              </view>
            </view>
          </view>
          <div class="bg-[#F4F6F8] w-full h-[.0625rem]"></div>
          <!-- 余额充足 -->
          <view class="flex flex-col gap-4 px-4" v-if="!showNoBalance">
            <!-- 商品信息 -->
            <view class="bg-[#F7F9FA] rounded-[.5rem] px-4 py-3 flex gap-2 justify-between items-center">
              <view class="flex gap-2 items-center">
                <image
                  :src="modelValueData.thumb"
                  class="w-[3.5rem] h-[3.5rem] rounded-[.375rem] overflow-hidden"
                  mode="aspectFill"
                />
                <view class="flex flex-col h-[3.5rem] justify-between">
                  <view class="text-[1rem] text-[#161A24] font-medium line-clamp-1">{{ modelValueData.name }}</view>
                  <view class="text-[.6875rem] text-[#8E9299]"> 永久有效 </view>
                </view>
              </view>
              <view
                class="text-[1.25rem] flex-none text-[#00A9AB] font-bold after:content-['钓钻'] after:text-[.5625rem]"
              >
                {{ Math.floor(modelValueData.paid_amount) }}
              </view>
            </view>
            <!-- 钓钻余额 -->
            <view class="bg-[#F7F9FA] rounded-[.5rem] h-[2.75rem] flex justify-between items-center px-4">
              <view class="text-[.875rem] text-[#161A24] font-bold">钓钻余额</view>
              <view class="text-[.75rem] text-[#8E9299]">{{ diamond }}钓钻</view>
            </view>

            <!-- 确认购买 -->
            <view class="mt-7">
              <view
                @click="confirmPurchase"
                class="h-[2.75rem] bg-[#00A9AB] rounded-full flex items-center justify-center"
                style="bottom: calc(env(safe-area-inset-bottom) / 2)"
              >
                <view class="text-[1rem] text-[#E5F6F6]">
                  余额支付 {{ Math.floor(modelValueData.paid_amount) }} 钓钻</view
                >
              </view>
            </view>
          </view>
          <!-- 余额不足 -->
          <view class="flex flex-col gap-4 px-4" v-if="showNoBalance">
            <!-- 钓钻余额 -->
            <view class="bg-[#F7F9FA] rounded-[.5rem] h-[2.75rem] flex justify-between items-center px-4">
              <view
                class="text-[1.25rem] text-[#161A24] font-bold after:ml-1 after:content-['钓钻'] after:text-[.75rem]"
              >
                {{ Math.floor(modelValueData.paid_amount) }}
              </view>
              <view class="flex gap-1 items-center">
                <view class="text-[.75rem] text-[#8E9299]"> 余额 {{ diamond }}</view>
                <view class="h-[.375rem] border-l"></view>
                <view class="text-[.75rem] text-[#8E9299]">
                  还需 {{ Math.floor(modelValueData.paid_amount) - diamond }}</view
                >
              </view>
            </view>
            <!-- 充值规格 -->
            <view class="flex flex-col gap-3">
              <view class="text-[.875rem] text-[#161A24] font-medium"> 充值规格 </view>
              <view class="grid grid-cols-3 gap-3 w-full">
                <view
                  class="rounded-[.5rem] flex flex-col gap-2 py-[.875rem] border-[.0625rem] relative"
                  @click="select(k)"
                  v-for="(i, k) in d.list"
                  :key="k"
                  :class="key == k ? 'border-[#00A9AB] bg-[#E6F7F7]' : ' border-transparent bg-[#F4F6F8]'"
                >
                  <view class="flex gap-1 justify-center items-center">
                    <view class="text-[1.125rem] text-[#161A24] font-bold"> {{ i.coin_base }} </view>
                    <view class="text-[.75rem] text-[#161A24] font-medium"> 钻 </view>
                  </view>
                  <view class="text-[.75rem] text-[#8E9299] text-center"> {{ i.price }}元 </view>
                  <!-- 推荐 -->
                  <view
                    v-if="bestMatchIndex == k"
                    class="absolute bg-[#00A9AB] rounded-[0rem_.5rem_0rem_.5rem] top-0 right-0 h-[.9375rem] px-[.4375rem] flex items-center"
                  >
                    <view class="text-[.5625rem] text-[#FFFFFF]"> 推荐 </view>
                  </view>
                </view>
              </view>
            </view>
            <!-- 支付方式 -->

            <view class="flex flex-col gap-2" v-if="platform == 'android'">
              <view class="text-[.75rem] text-[#8E9299]"> 选择支付方式 </view>
              <view class="flex justify-between py-3" v-for="(i, k) in data" @click="changePay(i)" :key="k">
                <view class="flex gap-2 items-center">
                  <view class="size-6 overflow-hidden rounded-full">
                    <image :src="i.icon" mode="aspectFill" class="size-full" />
                  </view>
                  <view class="text-[.875rem] text-[#161A24]">{{ i.name }}</view>
                </view>
                <view class="size-5 bg-[#FFFFFF] border rounded-full" v-if="!i.checked"></view>
                <view class="size-5 bg-[#00A9AB] border rounded-full grid place-content-center" v-if="i.checked">
                  <u-icon name="checkmark" color="#FFFFFF" class="mt-[.1875rem]" size="23"></u-icon>
                </view>
              </view>
            </view>
            <!-- 立即充值 -->
            <view class="mt-7">
              <button
                :class="disabled || disabledInit ? '!bg-[#00A9AB]/60' : '!bg-[#00A9AB]'"
                class="h-[2.75rem] rounded-full flex items-center justify-center after:border-none"
                style="bottom: calc(env(safe-area-inset-bottom) / 2)"
                :disabled="disabled || disabledInit"
                :loading="loading"
                hover-class="none"
                @click="rechargeNow"
              >
                <view v-if="loading" class="text-[1rem] text-[#E5F6F6]">充值中...</view>
                <view class="text-[1rem] text-[#E5F6F6]" v-else> 立即充值 {{ d.list[key]?.price }}元</view>
              </button>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
  import { Iap, IapTransactionState } from '/common/js/iap.js'

  export default {
    data() {
      return {
        modelValue_s: false, // 控制弹窗显示隐藏
        key: 0, // 当前选中的充值规格索引
        d: {
          diamond: 0, // 钻石数量
          list: [] // 充值规格列表
        },
        data: [
          {
            name: '微信', // 微信支付
            icon: '/static/dddr19.png',
            checked: true
          },
          {
            name: '支付宝', // 支付宝支付
            icon: '/static/dddr28.png',
            checked: false
          }
        ],
        title: '', // 弹窗标题
        showNoBalance: false, // 是否显示余额不足
        diamond: '', // 当前钻石余额
        platform: '', // 平台类型(android/ios)
        bestMatchIndex: 0, // 最佳匹配的充值规格索引
        loading: false, // 加载状态
        disabled: false, // 禁用状态
        productId: '', // 产品ID
        productList: [], // 产品列表
        productid: '', // 产品ID
        key: 0, // 产品ID
        disabledInit: false
        // h5Parameter: true
      }
    },
    props: {
      modelValue: {
        type: Boolean,
        default: false
      },

      modelValueData: {
        type: Object,
        default: {}
      }
    },
    created() {
      // #ifdef APP-PLUS
      this.platform = uni.getSystemInfoSync().platform // android   //ios
      // #endif
    },
    watch: {
      modelValue: {
        immediate: true,
        deep: true,
        handler(newValue, oldValue) {
          this.modelValue_s = newValue
          newValue && this.checkBalance()
        }
      }
    },
    methods: {
      select(k) {
        this.key = k
        this.productId = this.d.list[k].productid
      },
      async androidPayment() {
        let t = this
        t.loading = true
        t.disabled = true
        let createOrderRes = await api.createOrder({
          id: this.d.list[this.key].id
        })
        const payMethod = this.data.find(item => item.checked)
        const payType = payMethod.name === '微信' ? 'wechat' : 'alipay'

        const payParamsRes = await api.getPayParams({
          order_no: createOrderRes.data.order_no,
          pay_type: payType
        })
        if (payMethod.name === '微信') {
          uni.requestPayment({
            provider: 'wxpay',
            orderInfo: payParamsRes.data.params,
            success(res) {
              vk.toast('支付成功', 300, e => {
                t.rechargeSuccessful()
              })
            },
            fail(e) {
              vk.toast('支付失败')
            },
            complete() {
              t.loading = false
              t.disabled = false
            }
          })
        }
        if (payMethod.name === '支付宝') {
          // 调用支付宝支付
          uni.requestPayment({
            provider: 'alipay',
            orderInfo: payParamsRes.data.params, // 支付宝订单数据
            success: res => {
              vk.toast('支付成功', 300, e => {
                t.rechargeSuccessful()
              })
            },
            fail: err => {
              vk.toast('支付失败')
            },
            complete() {
              t.loading = false
              t.disabled = false
            }
          })
        }
      },
      // 苹果支付
      async iosPayment() {
        this.loading = true
        this.disabled = true
        let createOrderResult = await api.createOrder({
          id: this.d.list[this.key].id
        })
        vk.showLoading('支付处理中...')
        this._iap
          .requestPayment({
            productid: this.productId,
            manualFinishTransaction: true,
            username: createOrderResult.data.order_no
          })
          .then(async result => {
            uni.hideLoading()

            // // 在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
            let res = await api.applePay({
              receipt_data: result.transactionReceipt,
              order_no: result.payment.username,
              trid: result.transactionIdentifier,
              state: result.transactionState
            })
            console.log('res==> ', res)
            //验证成功后关闭订单
            await this._iap.finishTransaction(result)
            this.rechargeSuccessful()
          })
          .catch(err => {
            vk.hideLoading()
            console.log('🚀 ~ iosPayment ~ err:', err)
          })
          .finally(() => {
            this.loading = false
            this.disabled = false
          })
      },
      rechargeSuccessful() {
        this.checkBalance()
      },
      async rechargeNow() {
        vk.pubfn.debounce(() => {
          if (this.platform == 'android') {
            this.androidPayment()
          } else {
            this.iosPayment()
          }
        }, 500)
      },
      updateModelValue(value) {
        this.$emit('update:modelValue', value)
      },
      async checkBalance() {
        const res = await api.wallet()
        this.diamond = res.data.diamond
        console.log('this.modelValueData.paid_amount==> ', this.modelValueData.paid_amount)
        console.log('this.diamond==> ', this.diamond)
        if (this.modelValueData.paid_amount > this.diamond) {
          // 余额不足
          let diamondListRes = await api.getDiamondList()
          this.d = diamondListRes.data
          this.title = '钓钻充值'
          this.showNoBalance = true
          // 初始化ios
          if (this.platform == 'ios') {
            this._iap = new Iap({
              products: diamondListRes.data.list.map(item => item.productid) // 苹果开发者中心创建
            })
            this.init()
          }
          const neededDiamonds = Math.floor(this.modelValueData.paid_amount) - this.diamond

          let bestMatchIndex = 0
          let minExcessDiamonds = Infinity

          for (let i = 0; i < this.d.list.length; i++) {
            const option = this.d.list[i]
            if (option.coin_base >= neededDiamonds) {
              const excess = option.coin_base - neededDiamonds
              if (excess < minExcessDiamonds) {
                minExcessDiamonds = excess
                bestMatchIndex = i
              }
            }
          }

          if (minExcessDiamonds === Infinity && this.d.list.length > 0) {
            let maxDiamondsIndex = 0
            let maxDiamonds = 0

            for (let i = 0; i < this.d.list.length; i++) {
              if (this.d.list[i].coin_base > maxDiamonds) {
                maxDiamonds = this.d.list[i].coin_base
                maxDiamondsIndex = i
              }
            }

            bestMatchIndex = maxDiamondsIndex
          }

          // 设置推荐的充值选项
          this.bestMatchIndex = bestMatchIndex
          this.key = bestMatchIndex
        } else {
          // 余额充足
          this.title = '解锁后可查看钓点精准定位'
          this.showNoBalance = false
        }
      },
      // 验证订单
      async restore() {
        try {
          const transactions = await this._iap.restoreCompletedTransactions({
            username: ''
          })

          if (!transactions.length) return
          for (const element of transactions) {
            console.log('element==> ', element)
            switch (element.transactionState) {
              case IapTransactionState.purchased:
                console.log('11==> ', 11)
                let res = await api.applePay({
                  receipt_data: element.transactionReceipt,
                  order_no: element.payment.username,
                  trid: element.transactionIdentifier,
                  state: element.transactionState
                })
                console.log('res==> ', res)
                if (!res.code) return vk.toast(res.msg)
                await this._iap.finishTransaction(element)
                break
              case IapTransactionState.failed:
                console.log('22==> ', 22)

                // 关闭未支付的订单
                await this._iap.finishTransaction(element)
                break
              default:
                break
            }
          }
        } catch (e) {
          console.log('e==> ', e)
          uni.hideLoading()
        }
      },
      // 苹果初始化
      async init() {
        // vk.showLoading('检测支付环境...')
        this.disabledInit = true

        try {
          // 初始化，获取iap支付通道
          await this._iap.init()
          // 从苹果服务器获取产品列表
          this.productList = await this._iap.getProduct()
          console.log(' this.productList==> ', this.productList)
          this.productList[0].checked = true
          this.productId = this.d.list.map(item => item.productid)[this.key]
          // this.productId = this.d.list.map(item => item.productid)[0]
          // 填充产品列表，启用界面
        } catch (e) {
          uni.hideLoading()
        } finally {
          this.disabledInit = false
          uni.hideLoading()
        }

        if (this._iap.ready) {
          this.restore()
        }
      },
      confirmPurchase() {
        vk.pubfn.debounce(() => {
          api
            .unlockBasan({
              basan_id: this.modelValueData.id
            })
            .then(result => {
              if (!result.code) return
              vk.toast('解锁成功', 300, e => {
                this.paySuccess()
              })
            })
        }, 500)
      },
      // 支付成功
      paySuccess() {
        this.updateModelValue(false)
        this.$emit('paySuccess')
      },
      changePay(i) {
        this.data.forEach(item => {
          item.checked = false
        })
        i.checked = true
      },

      closeThePopUpBox() {
        this.$emit('update:modelValue', false)
      }
    }
    // beforeUnmount() {
    //   // 组件销毁时恢复滚动
    //   document.body.style.overflow = ''
    // }
  }
</script>

<style lang="scss" scoped></style>
